<template>
<div class="center">

<el-form ref="login" :model="loginUser"  :rules="loginRule">
  <el-form-item  prop="username"   >
    <div class="yonghu">
    <el-input  prefix-icon="iconfont icon-yonghu" class="wo" type="text" placeholder="输入用户名" v-model="loginUser.username"></el-input>
    </div>
  </el-form-item>
  <el-form-item   prop="password"  class="mima">
    <el-input   placeholder="输入密码" prefix-icon="iconfont icon-mima" v-model="loginUser.password" show-password></el-input>
  </el-form-item>
  <el-row >
    <el-col span="8">
  <el-form-item>
    <el-button type="primary" @click="login" >登录</el-button>
  </el-form-item>
    </el-col>
    <el-col span="8">
  <el-form-item>
    <el-button >注册</el-button>
  </el-form-item>
    </el-col>
    <el-col span="8">
  <el-form-item>
    <el-button type="info" @click="relogin">重置</el-button>
  </el-form-item>
      </el-col>
  </el-row>
</el-form>


</div>
</template>

<script>
export default {
  name: "Login",
  data(){
    return{
      loginUser:{
        username:"admin",
        password:"123456"
      },
      loginRule:{
        //trigger鼠标失去焦点是触发规则
        name:[
          { required:true,message:'请输入用户名',trigger:'blur'},
          { min:3,max:12,message: '长度在3到12个字符',trigger: 'blur'}
        ],
        password:[
          { required:true,message:'请输入用户名',trigger:'blur'},
          { min:3,max:12,message: '长度在3到12个字符',trigger: 'blur'}
        ]
      }
      }
    },
  methods:{
    relogin(){
this.$refs.login.resetFields();
    },
    login(){
      this.$refs.login.validate(async valid=>{
        if(valid==false){
          return;
        }
        //解构拿到data命名为res
        //请求地址为login（登录页面）
        const {data:res}= await this.$http.post('login',this.loginUser)
        console.log(res)
        //拿到状态码，可以通过状态码判断用户是否登录成功
       const rel=res.meta.status
        if(rel!==200){

        //if(rel!==400){
          //全局挂载message
          this.$message.error("登录失败")
          return console.log("失败")
        }else{
          this.$message.success("登录成功")
          //登录成功后的token保存在 sessstroage中
          //必须携带token才能访问其他地址（拦截器）
          window.sessionStorage.setItem("token",res.data.token)
          //通过导航跳转到home
          await this.$router.push("/home")
          return console.log("成功")


        }
      })


    }
  }


}

</script>

<style scoped>
.center{
  display: flex;
  width: 100%;
  height: 100%;
  align-items: center;
  justify-content: center;
}

</style>
